﻿#pragma once

#include <QObject>
#include <QTcpSocket>
#include <qtcpserver.h>
#include <QMutex>



class ClientPool;
class StateServer : public QObject
{
	Q_OBJECT

public:
	StateServer(quint16 port, QObject *parent = nullptr);
	~StateServer();

	Q_INVOKABLE bool Start();
	void Stop();
	void SetStateData(const QByteArray& data);

signals:
	void serviceStarted(const QString& message);
	void serviceStopped(const QString& message);
	void errorOccurred(const QString& error);
	void clientConnected();
	void clientDisconnected();

private slots:
	void HandleNewConnection();
	void pushStatusData();
private:
	quint16 m_port;
	QTcpServer* m_server = new QTcpServer(this);
	QSharedPointer<ClientPool> m_connectionPool = QSharedPointer<ClientPool>::create();
	QTimer* m_pushTimer = nullptr;
	QByteArray m_currentStatus;
};


class ClientPool : public QObject
{
	Q_OBJECT
public:
	ClientPool(QObject* parent = nullptr);
	~ClientPool();
	void AddClient(QTcpSocket* socket);
	void RemoveClinet(QTcpSocket* socket);
	void SendToAll(const QByteArray& data);

	int ClientCount() const;

signals:
	void clientCountChanged(int count);

private:
	QList<QTcpSocket*> m_clients;
	mutable QMutex m_mutex;
};
